//
//  SLRegisterViewController.m
//  StarLight
//
//  Created by Duke.wu on 16/5/10.
//  Copyright © 2016年 Duke.Wu. All rights reserved.
//

#import "SLRegisterViewController.h"
#import "SLCheseStatusViewController.h"
#import "SLLoginViewModel.h"
#import "SLUserDelegateViewController.h"



@interface SLRegisterViewController ()


@property (nonatomic, strong) UITextField *phoneTF;

@property (nonatomic, strong) UITextField *testNumTF;

@property (nonatomic, strong) UITextField *pswTF;

@property (nonatomic, strong) UITextField *aPswTF;

@property (nonatomic, strong) UIButton *sendTNumBtn;

@property (nonatomic, strong) UIButton *nextBtn;

@property (nonatomic, strong) UIButton *selectedBtn;

@property (nonatomic, strong) UILabel *tipLabel;

@property (nonatomic, strong) UIButton *delegateBtn;

@property (nonatomic, assign) ControllerType type;

@property (nonatomic, assign)NSInteger minute;

@end

@implementation SLRegisterViewController

static NSInteger waitTime = 120;

- (instancetype)initWithControllerType:(ControllerType)type{
  self = [super init];
  if (self) {
    self.type = type;
  }
  return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
  self.minute = waitTime;
  [self.view addSubview:self.phoneTF];
  [self.view addSubview:self.testNumTF];
  [self.view addSubview:self.pswTF];
  [self.view addSubview:self.aPswTF];
  [self.view addSubview:self.sendTNumBtn];
  [self.view addSubview:self.nextBtn];
  [self.view addSubview:self.delegateBtn];
  [self.view addSubview:self.selectedBtn];
  [self.view addSubview:self.tipLabel];
  
  [self addConstrains];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
  [super viewWillAppear:animated];
  [self changeType];
}

- (void)changeType{
  
  if (self.type == ControllerTypeForget) {
    self.title = @"找回密码";
    self.tipLabel.hidden = YES;
    self.selectedBtn.hidden = YES;
    self.delegateBtn.hidden = YES;
    [self.nextBtn setTitle:@"确定" forState:UIControlStateNormal];
  }else{
    self.title = @"注册";
  }
  
  self.view.backgroundColor = [UIColor whiteColor];
  UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toHideKeyBoard)];
  [self.view addGestureRecognizer:tapGes];

  
}

- (void)addConstrains{
  [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.height.equalTo(@34);
    make.top.equalTo(self.mas_topLayoutGuideBottom).offset(37);
    make.width.equalTo(self.view).offset(-54);
    make.centerX.equalTo(self.view);
  }];
  
  UIView *phoneLine = [UIView lineView];
  [self.view addSubview:phoneLine];
  [phoneLine mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.right.equalTo(self.phoneTF);
    make.top.equalTo(self.phoneTF.mas_bottom);
    make.height.equalTo(@1);
  }];
  
  [self.sendTNumBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.phoneTF.mas_bottom).offset(24);
    make.height.equalTo(self.phoneTF);
    make.width.equalTo(@100);
    make.right.equalTo(self.phoneTF);
  }];
  
  [self.testNumTF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.sendTNumBtn);
    make.height.equalTo(self.phoneTF);
    make.left.equalTo(self.phoneTF);
    make.right.equalTo(self.sendTNumBtn.mas_left).offset(-20);
  }];
  
  UIView *testLine = [UIView lineView];
  [self.view addSubview:testLine];
  [testLine mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.right.equalTo(self.testNumTF);
    make.top.equalTo(self.testNumTF.mas_bottom);
    make.height.equalTo(@1);
  }];
  
  [self.pswTF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.testNumTF.mas_bottom).offset(24);
    make.width.left.height.equalTo(self.phoneTF);
    
  }];
  UIView *pswLine = [UIView lineView];
  [self.view addSubview:pswLine];
  [pswLine mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.right.equalTo(self.pswTF);
    make.top.equalTo(self.pswTF.mas_bottom);
    make.height.equalTo(@1);
  }];
  
  [self.aPswTF mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(self.pswTF.mas_bottom).offset(24);
    make.width.left.height.equalTo(self.phoneTF);
  }];
  UIView *aPswLine = [UIView lineView];
  [self.view addSubview:aPswLine];
  [aPswLine mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.right.equalTo(self.aPswTF);
    make.top.equalTo(self.aPswTF.mas_bottom);
    make.height.equalTo(@1);
  }];
  
  [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.left.width.equalTo(self.pswTF);
    make.height.equalTo(@46);
    make.bottom.equalTo(self.view).offset(-60);
  }];
  
  [self.selectedBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.size.mas_equalTo(CGSizeMake(22, 22));
    make.left.equalTo(self.nextBtn);
    make.bottom.equalTo(self.nextBtn.mas_top).offset(-27);
  }];
  
  [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    make.centerY.equalTo(self.selectedBtn);
    make.left.equalTo(self.selectedBtn.mas_right).offset(10);
  }];
  
  [self.delegateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    make.bottom.equalTo(self.tipLabel);
    make.left.equalTo(self.tipLabel.mas_right);
    make.size.mas_equalTo(CGSizeMake(90, 20));
  }];
  
  
}

#pragma mark - private Methods

- (void)showUserServiceDelegate{
  SLUserDelegateViewController *delegateVC = [SLUserDelegateViewController new];
  [self.navigationController pushViewController:delegateVC animated:YES];
}

- (void)toHideKeyBoard{
  [self.view endEditing:YES];
}

- (void)selectedBtnWasTaped{
  self.selectedBtn.selected = !self.selectedBtn.selected;
}

// 底部Button 的点击事件
- (void)toNext{
  
  BOOL passw = self.pswTF.text.length > 5 && self.pswTF.text.length < 11;
  BOOL testE = [self.pswTF.text isEqualToString:self.aPswTF.text];
  BOOL test = self.testNumTF.text.length == 4;
  
  if (!passw) {
    [SVProgressHUD showErrorWithStatus:@"密码限制6~10位!"];
    return;
  }
  
  if (!testE) {
    [SVProgressHUD showErrorWithStatus:@"两次输入密码不一致!"];
    return;
  }
  
  if (!test) {
    [SVProgressHUD showErrorWithStatus:@"请输入正确验证码!"];
    return;
  }
  
  
  if (self.type == ControllerTypeForget) {
    // 满足所有的 条件之后才可以
    if ([SLLoginViewModel checkTelNumber:self.phoneTF.text] && (self.pswTF.text.length > 5 && self.pswTF.text.length < 11)  && self.testNumTF.text.length == 4 && [self.pswTF.text isEqualToString:self.aPswTF.text]) {
        [self forgetPswAction];
    }
  }else{
    if (!self.selectedBtn.selected) {
      [SVProgressHUD showErrorWithStatus:@"请同意用户协议"];
      return;
    }
    
    if ([SLLoginViewModel checkTelNumber:self.phoneTF.text] && (self.pswTF.text.length > 5 && self.pswTF.text.length < 11)  && self.testNumTF.text.length == 4 && [self.pswTF.text isEqualToString:self.aPswTF.text] && self.selectedBtn.selected) {
      [self toRegisterNextStep];
    }
  }
  
}


// 验证 验证码 和手机号, 如果正确 修改密码 然后调到登陆
- (void)forgetPswAction{
  
  NSDictionary *dic = @{@"phone" : self.phoneTF.text, @"code":self.testNumTF.text,@"psw":self.pswTF.text};
  
  @weakify(self)
  
  [SLLoginViewModel forgetPwsWithParameters:dic complete:^{
    @strongify(self)
    [self.navigationController popViewControllerAnimated:YES];
  }];
  
}

// 验证 验证码 和手机号, 如果正确 则下一步
- (void)toRegisterNextStep{
  

  NSDictionary *dic = @{@"phone":self.phoneTF.text,@"code":self.testNumTF.text};
//
  @weakify(self)
  [SLLoginViewModel testRegisterNumWithParameters:dic complete:^{
    @strongify(self)
    [DEFAULTS setObject:self.phoneTF.text forKey:@"phone"];
    [DEFAULTS setObject:self.testNumTF.text forKey:@"code"];
    [DEFAULTS setObject:self.pswTF.text forKey:@"password"];
    [DEFAULTS synchronize];
    SLCheseStatusViewController *choseVC = [SLCheseStatusViewController new];
    [self.navigationController pushViewController:choseVC animated:YES];
  }];
  
}


/**
 *  给testButton 添加定时器
 *  改变button的title
 *
 *  @param button testButton
 */
- (void)addTimer{
  [self.view endEditing:YES];
  
  if ([SLLoginViewModel checkTelNumber:self.phoneTF.text]) {
    //添加定时器
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timing:) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    
    self.sendTNumBtn.enabled = NO;
    [self.sendTNumBtn setTitle:[NSString stringWithFormat:@"%lds 从新获取",(long)_minute] forState:UIControlStateNormal];
    
    if (self.type == ControllerTypeRegister) {
      [SLLoginViewModel sendSMSWithPhoneNumberForRegister:self.phoneTF.text];
    }else{
      [SLLoginViewModel sendSMSWithPhoneNumberForForget:self.phoneTF.text];
    }
 
  }else{
    [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
  }
}

/**
 *  计时倒数秒
 */
- (void)timing:(NSTimer *)timer{
  self.minute -= 1;
  
  [self.sendTNumBtn setTitle:[NSString stringWithFormat:@"%lds",(long)self.minute] forState:UIControlStateNormal];
  if (self.minute < 0) {
    //关闭定时器
    [timer invalidate];
    timer = nil;
    
    //还原
    self.minute = waitTime;
    
    //重置button
    [self.sendTNumBtn setTitle:@" 获取验证码 " forState:UIControlStateNormal];
    self.sendTNumBtn.enabled = YES;
    
  }
  
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - getter

- (UITextField *)phoneTF{
  if (!_phoneTF) {
    _phoneTF = [UITextField new];
    _phoneTF.font = [UIFont boldSystemFontOfSize:16];
    _phoneTF.placeholder = @"手机";
    _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    _phoneTF.textColor = SLBlackColor;
  }
  return _phoneTF;
}

- (UITextField *)testNumTF{
  if (!_testNumTF) {
    _testNumTF = [UITextField new];
    _testNumTF.font = [UIFont boldSystemFontOfSize:16];
    _testNumTF.keyboardType = UIKeyboardTypeNumberPad;
    _testNumTF.placeholder = @"验证码";
    _testNumTF.textColor = SLBlackColor;
  }
  return _testNumTF;
}

- (UITextField *)pswTF{
  if (!_pswTF) {
    _pswTF = [UITextField new];
    _pswTF.font = [UIFont boldSystemFontOfSize:16];
    _pswTF.placeholder = @"密码 (10位数以内)";
    _pswTF.textColor = SLBlackColor;
  }
  return _pswTF;
}

- (UITextField *)aPswTF{
  if (!_aPswTF) {
    _aPswTF = [UITextField new];
    _aPswTF.font = [UIFont boldSystemFontOfSize:16];
    _aPswTF.placeholder = @"确认密码";
    _aPswTF.textColor = SLBlackColor;
  }
  return _aPswTF;
}

- (UIButton *)sendTNumBtn{
  if (!_sendTNumBtn) {
    _sendTNumBtn = [UIButton buttonWithTitle:@"获取验证码"];
    _sendTNumBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    _sendTNumBtn.backgroundColor = [UIColor lightGrayColor];
    [_sendTNumBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [_sendTNumBtn addTarget:self action:@selector(addTimer) forControlEvents:UIControlEventTouchUpInside];
  }
  return _sendTNumBtn;
}

- (UIButton *)nextBtn{
  if (!_nextBtn) {
    _nextBtn = [UIButton buttonWithTitle:@"下一步"];
    _nextBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    _nextBtn.backgroundColor = SLYellowColor;
    [_nextBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_nextBtn addTarget:self action:@selector(toNext) forControlEvents:UIControlEventTouchUpInside];
  }
  return _nextBtn;
}

- (UIButton *)selectedBtn{
  if (!_selectedBtn) {
    _selectedBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_selectedBtn setImage:[UIImage imageNamed:@"O"] forState:UIControlStateNormal];
    [_selectedBtn setImage:[UIImage imageNamed:@"click_get"] forState:UIControlStateSelected];
    [_selectedBtn addTarget:self action:@selector(selectedBtnWasTaped) forControlEvents:UIControlEventTouchUpInside];
    _selectedBtn.selected = YES;
  }
  return _selectedBtn;
}

- (UILabel *)tipLabel{
  if (!_tipLabel) {
    _tipLabel = [UILabel new];
    _tipLabel.text = @"我已阅读并接受";
    _tipLabel.font = [UIFont boldSystemFontOfSize:16];
  }
  return _tipLabel;
}




- (UIButton *)delegateBtn{
  if (!_delegateBtn) {
    _delegateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    NSMutableAttributedString *attriTitle = [[NSMutableAttributedString alloc] initWithString:@"用户协议"];
    NSRange titleRange = NSMakeRange(0, attriTitle.length);
    [attriTitle addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:titleRange];
    [attriTitle addAttribute:NSUnderlineColorAttributeName value:SLYellowColor range:titleRange];
    [attriTitle addAttribute:NSForegroundColorAttributeName value:SLYellowColor range:titleRange];
    [_delegateBtn addTarget:self action:@selector(showUserServiceDelegate) forControlEvents:UIControlEventTouchUpInside];
    [_delegateBtn setAttributedTitle:attriTitle forState:UIControlStateNormal];
    
  }
  return _delegateBtn;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
